import * as types from '@/store/mutation-type'
import axios from '@/helpers/http'

export default {
  state: {
    authenticated: false,
    name: null,
    nickname: null
  },
  mutations: {
    [types.UPDATE_PROFILE_NAME] (state, payload) {
      state.name = payload.value
    },
    [types.UPDATE_PROFILE_EMAIL] (state, payload) {
      state.nickname = payload.value
    },
    [types.SET_AUTH_USER] (state, payload) {
      state.authenticated = true
      state.name = payload.user.name
      state.nickname = payload.user.nickname
    },
    [types.UNSET_AUTH_USER] (state) {
      state.authenticated = false
      state.name = null
      state.nickname = null
    }
  },
  actions: {
    setAuthUser ({commit, dispatch}) {
      return axios.get('/api/v2/userifo').then(response => {
        commit({
          type: types.SET_AUTH_USER,
          user: response.data.data
        })
      }).catch(error => {
        console.log(error)
        dispatch('refreshToken')
      })
    },
    unsetAuthUser ({commit}) {
      commit({
        type: types.UNSET_AUTH_USER
      })
    },
    refreshToken ({commit, dispatch}) {
      return axios.post('/api/v2/token/refresh').then(response => {
        dispatch('loginSuccess', response.data)
      }).catch(error => {
        console.log(error)
        dispatch('logoutRequest')
      })
    }
  }
}
